from lib.settings import HAOBTC_API_URL
import config
import json
import hashlib
import urllib
import urllib.request
import ssl

def buildSign(params, secretKey):
    sign = ''
    for key in sorted(params.keys()):
        sign += key + '=' + str(params[key]) +'&'
    data = sign+'secret_key='+secretKey
    return hashlib.md5(data.encode("utf8")).hexdigest().upper()


def request(uri, params):
    sign = buildSign(params, config.HAOBTC_SECRET_TOKEN)
    params['sign'] = sign
    context = ssl._create_unverified_context()
    response = urllib.request.urlopen(HAOBTC_API_URL['host']+uri, urllib.parse.urlencode(params).encode('utf-8'),
                                      context=context, timeout=3)
    if response.status == 200:
        mybytes = response.read()
        mystr = mybytes.decode("utf-8")
        response.close()
        return json.loads(mystr)
    else:
        response.close()
        return False


def getDepth(uri, params):
    context = ssl._create_unverified_context()
    response = urllib.request.urlopen(HAOBTC_API_URL['host']+uri, urllib.parse.urlencode(params).encode('utf-8'), context=context, timeout=1)
    if response.status == 200:
        mybytes = response.read()
        mystr = mybytes.decode("utf-8")
        response.close()
        return json.loads(mystr)
    else:
        response.close()
        return False
